package com.itobase.questionnaire.controller;

import com.itobase.questionnaire.VO.PageDatas;
import com.itobase.questionnaire.VO.UserVO;
import com.itobase.questionnaire.config.MyProps;
import com.itobase.questionnaire.model.*;
import com.itobase.questionnaire.model.EnumList.States;
import com.itobase.questionnaire.model.auth.User;
import com.itobase.questionnaire.repository.*;
import com.itobase.questionnaire.service.ISurveyService;
import com.itobase.questionnaire.service.impl.SurveyGroupService;
import com.itobase.questionnaire.template.Constant;
import com.itobase.questionnaire.util.*;
import jdk.nashorn.internal.objects.annotations.Where;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.MessageFormat;
import java.text.ParseException;
import java.util.*;

/**
 * @author liucong
 * @date 2018/7/30
 */

@RestController
@RequestMapping(value = "survey")
public class SurveyController {

    @Autowired
    ISurveyService surveyService;

    @Autowired
    SurveyRepository surveyRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    QuesnaireRepository quesnaireRepository;

    @Autowired
    UrlRepository urlRepository;

    @Autowired
    SectionRateRepository sectionRateRepository;

    @Autowired
    SurveyGroupService surveyGroupService;

    @Autowired
    SubmitRepository submitRepository;

    @Autowired
    MyProps myProps;

    @Autowired
    MongoTemplate template;





    @GetMapping("type")
    public Message getSurveyByType(@PageableDefault(page =1)Pageable pageable, @RequestParam Boolean privately) {
        List<Survey> list = surveyRepository.findByPrivately(privately,new Sort(Sort.Direction.DESC,"createTime"));
        if(list.size()!=0) {
            PageDatas<Survey> pageDatas = PagingUtils.paging(pageable.getPageNumber(), list, pageable.getPageSize());
            return Message.createSuc(pageDatas);
        }else{
            return Message.createSuc("没有符合该条件的调查");
        }
    }

    //新建调查
    @PostMapping("build")
    public Message buildSurvey(@RequestBody Survey survey) throws Throwable {
        final String url = "http://" + myProps.getIp() + "/"; // 结尾必需带 /
        survey.setUserId(AuthUtil.getUserId());
        String id  = survey.getQuestionsID();
        Questionnaire questionnaire = quesnaireRepository.findById(id);
        if(questionnaire==null){
            return Message.createErr("问卷的id错误");
        }else {
            Survey survey_1 = surveyRepository.findByTitle(survey.getTitle());
            if (survey_1 != null) {
                return Message.createSuc("该调查名已存在");
            } else {
                if(survey.getStartTime().length()==0||survey.getEndTime().length()==0){
                    return Message.createErr("调查周期不能为空");
                }
                Date current_day = new Date();
                Date begin_day = DateUtil.parse_day(survey.getStartTime());
                Date end_day = DateUtil.parse_day(survey.getEndTime());
                if(begin_day.compareTo(end_day)>=0){
                    return Message.createErr("调查开始时间不能大于结束时间");
                }
                questionnaire.setUsed(true);
                quesnaireRepository.save(questionnaire);
                if (current_day.compareTo(begin_day) > 0 && current_day.compareTo(end_day) < 0) {
                    survey.setState(States.running);
                } else if (current_day.compareTo(begin_day) < 0) {
                    survey.setState(States.notStarted);
                } else if (current_day.compareTo(end_day) > 0) {
                    survey.setState(States.ended);
                }
                ShortUrl shortUrl = new ShortUrl();
                Survey resSurvey = surveyRepository.insert(survey);
                String surveyId = resSurvey.getId();
                shortUrl.setSurveyId(surveyId);
                shortUrl.setLongUrl(surveyId);
                shortUrl.setShortUrl(MD5Util.getShortUrl(surveyId));
                urlRepository.insert(shortUrl);
                resSurvey.setUrl(url.concat("q/" + shortUrl.getShortUrl()));
                resSurvey.setCreateTime(new Date());
                resSurvey = surveyRepository.save(resSurvey);
                return Message.createSuc(resSurvey);
            }
        }

    }

    @GetMapping("sections")
    public Message getAllSections(){
        List<SectionRate> sectionRates = sectionRateRepository.findAll();
        List<String> allSectionNames = new ArrayList<>();
        sectionRates.forEach(sectionRate -> allSectionNames.add(sectionRate.getSectionName()));
        return Message.createSuc(allSectionNames);
    }


    //根据调查id删除调查
    @DeleteMapping("delete")
    public Message deleteSurvey(@RequestParam String id) {
        Survey survey = surveyRepository.findById(id);
        if(survey==null){
            return Message.createSuc("调查id出错，未找到该问卷");
        }else {
            int flag=0;
            String que_id = survey.getQuestionsID();
            List<Survey> list = surveyRepository.findAll();
            for( Survey i : list){
                if(que_id.equals(i.getQuestionsID())){
                    flag++;
                }
            }
            if(flag==1) {
                Questionnaire questionnaire = quesnaireRepository.findOne(que_id);
                questionnaire.setUsed(false);
                quesnaireRepository.save(questionnaire);
            }
            template.remove(Query.query(Criteria.where("surveyId").is(id)),Submission.class);
            surveyRepository.delete(id);
            surveyService.deleteSendPool(survey.getTitle());
            if(urlRepository.findBySurveyId(id)!=null){
                urlRepository.delete(urlRepository.findBySurveyId(id));
            }
            return Message.createSuc("删除成功");
        }
    }

    //更新调查内绑定的问卷
    @PutMapping("update")
    public Message updateQuestionnaire(@RequestBody Map<String,Object> map) throws IOException {
        String id = (String)map.get("id");
        MultipartFile file = (MultipartFile) map.get("file");
        return Message.createSuc(surveyService.updateQuestionnaire(id, file));
    }
    //更新调查周期
    @PutMapping("setTime")
    public Message setNewTime(@RequestParam String id,@RequestParam String startTime,@RequestParam String endTime) throws ParseException {
        return surveyService.updateTime(id,startTime,endTime);
    }

    //根据调查类型和状态筛选调查
    @GetMapping("select")
    public Message selectByPrivatelyAndStates(@PageableDefault(page =1) Pageable pageable, @RequestParam(required = false) Boolean privately, @RequestParam(required = false) States state) {
        List<Survey> list;
        if(privately!=null&&state!=null){
            list = surveyRepository.findByPrivatelyAndState(privately, state,new Sort(Sort.Direction.DESC,"createTime"));
        }else if(privately==null&&state==null){
            list = surveyRepository.findAll(new Sort(Sort.Direction.DESC,"createTime"));
        }else{
            list = surveyRepository.findByPrivatelyOrState(privately, state,new Sort(Sort.Direction.DESC,"createTime"));
        }
        if(list.size()!=0){
            PageDatas<Survey> pageDatas = PagingUtils.paging(pageable.getPageNumber(),list,pageable.getPageSize());
            return Message.createSuc(pageDatas);
        }else{
            return Message.createSuc("无符合该条件的调查");
        }
    }

    //查看调查详情
    @GetMapping("detail")
    public Message survey_detail(@RequestParam String id) {
        Survey survey = surveyRepository.findById(id);
        if(survey==null){
            return Message.createSuc("调查id出错,未找到该id");
        }else {
            return Message.createSuc(survey);
        }
    }

    //根据关键词搜索调查
    @GetMapping("search")
    public Message search_survey(@PageableDefault(page =1)Pageable pageable,@RequestParam(required = false) String word) {
        List<Survey> list = surveyRepository.findAll();
        List<Survey> list_new = new ArrayList<>();
        for (int i = list.size()-1; i>=0; i--) {
            if (list.get(i).getTitle().indexOf(word) != -1) {
                list_new.add(list.get(i));
            }
        }
        PageDatas<Survey> pageDatas = PagingUtils.paging(pageable.getPageNumber(),list_new,pageable.getPageSize());
        return Message.createSuc(pageDatas);
    }

    //重命名调查
    @PutMapping("rename")
    public Message rename(@RequestParam String id,@RequestParam String title) {
        Survey survey = surveyRepository.findById(id);
        if(survey==null){
            return Message.createSuc("调查id出错,未找到该id");
        }else {
            Survey survey_1 = surveyRepository.findByTitle(title);
            if (survey_1 != null) {
                return Message.createSuc("该调查名已存在");
            } else {
                survey.setTitle(title);
                return Message.createSuc(surveyRepository.save(survey));
            }
        }
    }

    //获取调查列表
    @GetMapping("list")
    public Message survey_list(@PageableDefault(page =1,sort = "createTime",direction = Sort.Direction.DESC)Pageable pageable)throws Exception{
        PageRequest pageRequest = new PageRequest(pageable.getPageNumber()-1,pageable.getPageSize(),pageable.getSort());
        Page<Survey> surveyList = surveyRepository.findAll(pageRequest);
        for(int i=0;i<surveyList.getContent().size();i++){
            Survey survey = surveyList.getContent().get(i);
            Date current_day = new Date();
            Date begin_day = DateUtil.parse_day(survey.getStartTime());
            Date end_day = DateUtil.parse_day(survey.getEndTime());
            if(!(survey.getState().equals(States.paused))) {
                if (current_day.compareTo(begin_day) > 0 && current_day.compareTo(end_day) < 0) {
                    survey.setState(States.running);
                } else if (current_day.compareTo(begin_day) < 0) {
                    survey.setState(States.notStarted);
                } else if (current_day.compareTo(end_day) > 0) {
                    survey.setState(States.ended);
                }
                surveyRepository.save(survey);
                survey.setUserList(Collections.emptyList());
                survey.setUserList_informed(Collections.emptyList());
            }
        }


        return Message.createSuc(surveyList);
    }

    //通过按钮更改状态即运行，暂停
    @PutMapping("changeStates")
    public Message changeStates(@RequestParam String id){
        Survey survey = surveyRepository.findById(id);
        if(survey==null){
            return Message.createSuc("调查id出错,未找到该id");
        }else {
            if (survey.getState().equals(States.notStarted)) {
                survey.setStartTime(DateUtil.format_day(new Date()));
                survey.setState(States.running);
            } else if (survey.getState().equals(States.running)) {
                survey.setState(States.paused);
            } else if (survey.getState().equals(States.paused)) {
                survey.setState(States.running);
            } else if (survey.getState().equals(States.ended)) {
                survey.setState(States.ended);
            }
            return Message.createSuc(surveyRepository.save(survey));
        }
    }

    //绑定用户列表
    @SuppressWarnings("unchecked")
    @PutMapping("userList")
    public Message setUserList(@RequestParam String id,@RequestParam(required = false,defaultValue = "未指定") String surveyGroupId){
        List<Survey> ifSurveyGroupIdUsed = surveyRepository.findBySurveyGroupId(surveyGroupId);
        if(ifSurveyGroupIdUsed!=null && ifSurveyGroupIdUsed.size()!=0){
            return Message.createErr("一个调查组仅允许绑定一个调查");
        }
        Survey survey = surveyRepository.findById(id);
        survey.setSurveyGroupId(surveyGroupId);
        List<User> userList = new ArrayList<>();
        if(survey.getUserList()!=null){
            userList = survey.getUserList();
        }
        if(surveyGroupId!=null){
            List<String> userIds = surveyGroupService.getUsersById(surveyGroupId);
            //System.out.println("获取UserIds大小"+userIds.size()+"--------------");
            Map<String,Integer> complicatedIds = new HashMap<>();
            List<User> extraUsers = new ArrayList<>();
            userIds.forEach(s -> {
                if(complicatedIds.containsKey(s)){
                    int oldNumber = complicatedIds.get(s);
                    oldNumber++;
                    extraUsers.add(Optional.ofNullable(userRepository.findOne(s)).orElseThrow(()->new RuntimeException("人员id不存在")));
                    complicatedIds.put(s,oldNumber);
                }else{
                    complicatedIds.put(s,1);
                }
            });
            userList.addAll(userRepository.findByIdIn(userIds.toArray(new String[0])));
            userList.addAll(extraUsers);
            //System.out.println("获取UserIds大小"+userList.size()+"--------------");
        }
        survey.setUserList(userList);
        return Message.createSuc(surveyRepository.save(survey));
    }

    //获取调查绑定的所有人员
    @GetMapping("getUserList")
    public Message getUserList(@PageableDefault(page =1)Pageable pageable,@RequestParam(required = false) String keyword,@RequestParam String surveyId,@RequestParam(required = false)String group){
        Pageable pageable_1 = new PageRequest(0,1000,pageable.getSort());
        Survey survey = surveyRepository.findById(surveyId);
        List<User> userList = survey.getUserList();
        if(userList.isEmpty()){
            return Message.createSuc("调查绑定人员列表为空");
        }
        List<UserVO> userList_final = new ArrayList<>();
        if(group==null) {
            //userList.removeAll(survey.getUserList_informed());
            List<String> ids_1 = new ArrayList<>();
            List<String> ids_2 = new ArrayList<>();
            if (userList != null) {
                for (User user : userList)
                    ids_1.add(user.getId());
                Page<User> user_informing = userRepository.findByIdIn(pageable_1, ids_1.toArray(new String[0]));
                for (User user : user_informing) {
                    UserVO userVO = new UserVO();
                    userVO.reconvert(user);
                    userVO.setInformed(Constant.DEFAULT_SEND);
                    userList_final.add(userVO);
                }
            }
            List<User> userList_informed = survey.getUserList_informed();
            if (userList_informed != null) {
                for (User user : userList_informed)
                    ids_2.add(user.getId());
                Page<User> user_inform = userRepository.findByIdIn(pageable_1, ids_2.toArray(new String[0]));
                for (User user : user_inform) {
                    UserVO userVO = new UserVO();
                    userVO.reconvert(user);
                    userVO.setInformed(Constant.SUCCESS_SEND);
                    userList_final.add(userVO);
                }
            }
        }else{
            userList_final = surveyGroupService.getUsersBySurveyGroupId(survey.getSurveyGroupId(),group,keyword);
        }
        if(keyword!=null){
            List<UserVO> user_list = new ArrayList<>();
            for(UserVO userVO : userList_final){
                if(userVO.getUsername().indexOf(keyword) != -1
                        ||userVO.getName().indexOf(keyword)!=-1
                        ||userVO.getCollegeName().indexOf(keyword)!=-1
                        ||userVO.getLongPhone().indexOf(keyword)!=-1
                        ||userVO.getUserType().indexOf(keyword)!=-1){
                    user_list.add(userVO);
                }
            }
            ListUtil.removeDuplicateWithOrder(user_list);
            PageDatas<UserVO> pageDatas_1 = PagingUtils.paging(pageable.getPageNumber(), user_list, pageable.getPageSize());
            return Message.createSuc(pageDatas_1);
        }else {
            ListUtil.removeDuplicateWithOrder(userList_final);
            PageDatas<UserVO> pageDatas = PagingUtils.paging(pageable.getPageNumber(), userList_final, pageable.getPageSize());
            return Message.createSuc(pageDatas);
        }

    }

    //清楚调查绑定人员列表
    @PostMapping("deleteUserList")
    public Message deleteUserList(@RequestParam String id){
        Survey survey = surveyRepository.findOne(id);
        if(survey==null){
            return Message.createSuc(MessageFormat.format("不存在该调查id={0}",id));
        }
        List<Submission> list = submitRepository.findBySurveyId(id);
        List<User> list_1 = survey.getUserList_informed();
        if(list.isEmpty()&&list_1.isEmpty()){
            survey.setUserList(Collections.emptyList());
            survey.setSurveyGroupId("");
            surveyRepository.save(survey);
            return Message.createSuc("人员列表删除成功");
        }else if(list.isEmpty()==false){
            return Message.createSuc("该调查已有答卷，删除失败");
        }else{
            return Message.createSuc("该调查已向被调查人员发出短信,删除失败");
        }
    }





}

